package com.study.talk.common.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study.talk.common.security.MyUserDetails;
import com.study.talk.module.entity.User;
import com.study.talk.module.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.HashSet;

@Component
public class TokenUtil {

    @Autowired
    private UserService userLoginService;

    public  Authentication getTokenAuthentication(String userName){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User user = userLoginService.getOne(wrapper.eq("username", userName));
        MyUserDetails userDetails = new MyUserDetails();
        userDetails.setUser(user);
        userDetails.setUsername(user.getUsername());
        userDetails.setPassword(user.getPassword());
        HashSet<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(new SimpleGrantedAuthority(user.getUsername()));
        userDetails.setAuthorities(authorities);
        return new UsernamePasswordAuthenticationToken(userDetails,userDetails.getPassword(),userDetails.getAuthorities());
    }

}
